// 微信公众号配置信息
var appId = "your_app_id";
var secret = "your_secret";
var redirectUri = "your_redirect_uri";
// 微信授权登录URL
var loginUrl = `https://open.weixin.qq.com/connect/qrconnect?appid=${appId}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_login&connect_redirect=1#wechat_redirect`;
// 跳转到微信授权页
window.location.href = loginUrl;
// 监听微信授权返回事件
window.onWeixinLoginSuccess = function (res) {
  // 获取code
  var code = res.code;
  // 通过code换取access_token和openid
  var accessTokenUrl = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${appId}&secret=${secret}&code=${code}&grant_type=authorization_code`;
  var xhr = new XMLHttpRequest();
  xhr.open("GET", accessTokenUrl, true);
  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
      var data = JSON.parse(xhr.responseText);
      var accessToken = data.access_token;
      var openid = data.openid;
      // 通过access_token和openid获取用户基本信息
      var userinfoUrl = `https://api.weixin.qq.com/sns/userinfo?access_token=${accessToken}&openid=${openid}&lang=zh_CN`;
      xhr.open("GET", userinfoUrl, true);
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
          var userinfo = JSON.parse(xhr.responseText);
          // 将用户信息保存到数据库或进行其他处理
          // ...
          // 登录成功，返回用户信息或跳转到主页
          // ...
        }
      };
      xhr.send();
    }
  };
  xhr.send();
};
